<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/30
 * Time: 下午2:12
 */

namespace common\models\search;


use common\helpers\OrderHelper;
use common\models\Package;
use common\models\VipOrder;
use frontend\models\search\PackageSearch;

class VipOrderForm extends VipOrder{
    
    /** @var VipOrder */
    private $_order;
    private $_package;
    public function rules(){
        return [
            [['package_id', 'user_id'], 'required'],
            [['package_id', 'user_id'], 'integer'],
            ['package_id', 'exist', 'targetClass' => Package::className(), 'targetAttribute' => 'package_id' ]
        ];
    }
    
    public function order()
    {
        if( !$this->validate() ){
            return false;
        }
        // 查询价格
        $field = \Yii::$app->user->identity->getPackageGroup();
        $price = $this->getPackage()->$field;
        $this->_order = new VipOrder;
        $this->_order->attributes = [
            'user_id' => $this->user_id,
            'money' => $price,
            'package_id' => $this->package_id,
            'order_sn' => OrderHelper::generateOrderSn()
        ];
        return $this->_order->save();
    }
    
    public function getOrder()
    {
        return $this->_order;
    }
    
    /**
     * @return Package
     */
    public function getPackage()
    {
        if( $this->_package === null ){
            $this->_package = Package::findOne(['package_id' =>$this->package_id]);
        }
        return $this->_package;
    }
}